var prefix = ctx +"module/device/range";
$().ready(function() {
    // validateRule();
    layui.use(['form','laydate','table'], function() {
        var form = layui.form,laydate = layui.laydate, table = layui.table;

        laydate.render({
            elem: '#begin_date',
            value: new Date(),
            isInitValue: true,
        });
        laydate.render({
            elem: '#end_date',
            value: new Date(),
            isInitValue: true,
        });


        var searchParams = {};
        searchParams['search_eq_deviceId']=$('#deviceId').val();

        //初始化table
        table.render({
            elem: '#exampleTable',//承载数据的table Id
            url: prefix + "/charts/result/list",//请求数据连接
            // toolbar: '#toolbarDemo',
            cellMinWidth: 80,//全局定义所有常规单元格的最小宽度（默认：60）
            even: true,//是否开启隔行变色
            loading:true,//是否显示加载条
            where :{
                searchParams:searchParams,
                sorts:{"create_time":"desc"}
            },
            defaultToolbar: false,
            //page: true,//是否分页
            page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                // 'skip','limit'
                layout: [ 'prev', 'page', 'next',  'count'] //自定义分页布局
            },
            limit: 8,
            cols: [[
                // {type:'numbers',title: '序号', width:'5%'},
                { field : 'height',  title : '测量高度',align : 'center',
                    templet: function (item) {
                        return (item.height) + ' 米';
                    },
                },
                { field : 'weight',  title : '剩余重量',align : 'center',
                    templet: function (item) {
                        // console.log('weight',item)
                        //筒仓  满仓状态  0 -  空仓  1 -  正常状态 2 - 满仓
                        if(item.storeState == 0){
                            if(item.isShowEmpty == 0){
                                return (item.weight) + ' 吨';
                            }
                            return '当前已空仓';
                        } else if(item.storeState == 2){
                            if(item.isShowFull == 0){
                                return (item.weight) + ' 吨';
                            }
                            return '当前已满仓';
                        } else {
                            return (item.weight) + ' 吨';
                        }
                    },
                },
                { field : 'createTime',  title : '测量时间', align : 'center', },
                // { field : 'telphone', title : '联系电话', align : 'center', },
                { title: '操作', minWidth: 100, templet: '#currentTableBar', fixed: "right", align: "center"}
            ]],
            id: 'currentTableId',//表格Id
        });

        form.on('select(isEllipse)', function (data) {
            isEllipseChange(data.value,form)
        });

        /**
         * 操作栏tool  监听事件
         */
        table.on('tool(currentTableFilter)', function (obj) {
            if (obj.event === 'chart') {  // 图表
                chart(obj.data.id);
            }
        });
    });
});




function reLoad() {
    var searchParams = {};
    searchParams['search_eq_deviceId']=$('#deviceId').val();

    layui.use(['table'], function() {
        var table = layui.table;//载入table模块

        var  page = $(".layui-laypage-skip").find("input").val() //当前页码值
        console.log('page',page)
        table.reload('currentTableId', {
            page: {curr: page}
            , where: {
                searchParams: searchParams
            }
        }, 'data');
    });
}


function chart(id) {
    var index = layer.open({
        type : 2,
        title : '当前测量数据走势',
        maxmin : true,
        shadeClose : false, // 点击遮罩关闭层
        area : [ '800px', '550px' ],
        content : prefix + '/charts3d/' + id // iframe的url
    });
    layer.full(index);
}




function handleDevice(deviceId) {
    // console.log("handleDevice",deviceId);
    var url = ctx +"module/device/range/detail/" + deviceId;
    $.ajax({
        // cache : true,
        type : "GET",
        url : url,
        // async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            console.log("handleDevice",data);
            if (data.code == 0) {

                console.log('data.device',data.device)

                $("#deviceId").val(data.device.id);
                $("#device").val(data.deviceStr);


                $("#lbStoreCylinderHeight").text('仓高: ' + data.device.cylinderHeight + 'm');

                $("#lbDeviceName").text(data.device.deviceName + ' ' + data.device.deviceNum);
                // $("#lbVolume").text('剩余体积: ' + data.device.lastVolumeNew + ' m³');

                if(data.device.storeState == 0){
                    if(data.device.isShowEmpty == 0){
                        $("#lbWeight").text('剩余吨数: ' + (data.device.totalWeight) + ' 吨');
                    }else{
                        $("#lbWeight").text('剩余吨数: ' + ' 当前已空仓');
                        // $("#lbVolume").text('剩余体积: ' + ' 当前已空仓');
                    }
                } else if(data.device.storeState == 2){
                    if(data.device.isShowFull == 0){
                        $("#lbWeight").text('剩余吨数: ' + (data.device.totalWeight) + ' 吨');
                    }else{
                        $("#lbWeight").text('剩余吨数: ' + ' 当前已满仓');
                        // $("#lbVolume").text('剩余体积: ' + ' 当前已满仓');
                    }
                }else{
                    $("#lbWeight").text('剩余吨数: ' + (data.device.totalWeight) + ' 吨');
                }


                if(data.device.deviceType == 0) {//粮仓
                    $("#lbTemperature").text('当前温度: ' + data.device.temperature + ' ℃');
                    $("#lbWeed").text('当前湿度: ' + data.device.humidity + ' %');
                }

                $("#lbStoreHeight").text(data.deviceHeight);

                if(data.device.isLie == 0){//立式
                    $("#divLie0").removeClass("layui-hide");
                    $("#divLie1").addClass("layui-hide");

                    if(data.device.deviceType == 0){//粮仓
                        console.log('isLie = 0   data.device.deviceType',data.device.deviceType)
                        $("#divHeightColor").css("top", ((1 - data.heightRate) * 200) +'px');
                        $("#store-view").css("top", 75 + ((1 - data.heightRate) * 200) +'px');
                    }else{//油仓
                        console.log('isLie = 0   data.device.deviceType',data.device.deviceType)
                        $("#divHeightColor").css("top", ((1 - data.heightRate) * 233) +'px');
                        $("#store-view").css("top", 75 + ((1 - data.heightRate) * 233) +'px');
                    }
                }else{//卧式
                    // $("#divLie0").css("display","none");
                    // $("#divLie1").css("display","block");

                    $("#divLie0").addClass("layui-hide");
                    $("#divLie1").removeClass("layui-hide");

                    if(data.device.deviceType == 0) {//粮仓
                        console.log('isLie = 1   data.device.deviceType',data.device.deviceType)
                        $("#divHeightColor").css("top", 72 + ((1 - data.heightRate) * 200) + 'px');
                        $("#store-view-lie").css("top", ((1 - data.heightRate) * 200) + 'px');
                    }else{//油仓
                        console.log('isLie = 1   data.device.deviceType',data.device.deviceType)
                        $("#divHeightColor").css("top", ((1 - data.heightRate) * 100) + 'px');
                        $("#store-view-lie").css("top", ((1 - data.heightRate) * 100) + 'px');
                    }
                }
                reLoad();
            } else {

            }
        }
    });
}

function goDeviceRecord() {

}

function startMeasure() {
    var deviceId = $("#deviceId").val();
    $.ajax({
        url : prefix + "/measure",
        type : "post",
        data : {
            'id' : deviceId
        },
        success : function(r) {
            if (r.code==0) {
                layer.msg('正在测量中，请稍后.......');
                setTimeout(function () {
                    reLoad();
                },50000)
            }else{
                layer.msg(r.msg);
            }
        }
    });
}

function isEllipseChange(isEllipse) {
    console.log('isEllipse',isEllipse);
    if(isEllipse == 1){
        $("#ellipseDiv").removeClass("layui-hide");
        $("#storeDiv").addClass("layui-hide");

    }else{
        $("#ellipseDiv").addClass("layui-hide");
        $("#storeDiv").removeClass("layui-hide");
    }
}

function update() {
	var url = ctx +"module/device/range/" + ($('#signupForm').find("#id").val() == '' ? "save" : "update");
    $.ajax({
        cache : true,
        type : "POST",
        url : url,
        data : $('#signupForm').serialize(),// 你的formid
        async : false,
        error : function(request) {
            parent.layer.alert("Connection error");
        },
        success : function(data) {
            if (data.code == 0) {
                parent.layer.msg("操作成功");
                parent.reLoad();
                var index = parent.layer.getFrameIndex(window.name); // 获取窗口索引
                parent.layer.close(index);
            } else {
                parent.layer.alert(data.msg)
            }
        }
    });

}

function goBack() {
    var deviceType = $("#deviceType").val();
    window.location.href = ctx + "module/device/range/shop/list/" + deviceType;
}

function validateRule() {
    var icon = "<i class='fa fa-times-circle'></i> ";
    $("#signupForm").validate({
        rules : {
            sort : {
                required : true
            }
        },
        messages : {
            sort : {
                required : icon + "请输入索引"
            }
        }
    })
}
